package com.wonders.frame.service;


import com.gcr.server.response.Response;
import com.wonders.frame.common.Enum.RemovedCodeEnum;
import com.wonders.frame.entity.AuthAccount;
import com.wonders.frame.entity.AuthAccountRole;
import com.wonders.frame.entity.AuthOrga;
import com.wonders.frame.entity.form.AuthAccountForm;
import com.wonders.frame.repository.AuthAccountRoleRepository;
import com.wonders.frame.repository.core.CoreRepository;
import com.wonders.frame.service.Core.CoreCurdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.*;

@Service
public class AuthAccountRoleService extends CoreCurdService<AuthAccountRole> {

    @Autowired
    private AuthAccountRoleRepository repository;
    @Override
    protected CoreRepository<AuthAccountRole> getRepository() {
        return repository;
    }

    public List<AuthAccountRole> findByAccountId(String accountId){
        return repository.findByAccountId(accountId);
    }

    public void saveAuthAccountRole(String accountId,String[]roleIds){
        //根据accountId删除之前绑定的role
        repository.deleteByAccountId(accountId);

        //判断数组是否有值
        if(roleIds.length>0){
            //把修改后的role绑定回去
            List<AuthAccountRole> list=new ArrayList<>();
            for (String roleId:roleIds){
                AuthAccountRole authAccountRole=new AuthAccountRole();
                authAccountRole.setAccountId(accountId);
                authAccountRole.setRoleId(roleId);
                authAccountRole.setCrtDate(new Date());
                authAccountRole.setUpdDate(new Date());
                authAccountRole.setRemoved(RemovedCodeEnum.AVAILABLE.getCode());
                list.add(authAccountRole);
            }
            repository.saveAll(list);
        }

    }


    public List<AuthAccountRole> getAccountRole(){
        return repository.findAll();
    }

    //批量给用户添加角色
    public void batchAddRole(String[] accountIds ,String roleId){
        System.out.println("************"+accountIds.length+"------"+roleId);
        for(String accountId:accountIds){
            AuthAccountRole authAccountRole=new AuthAccountRole();
            authAccountRole.setAccountId(accountId);
            authAccountRole.setRoleId(roleId);
            authAccountRole.setRemoved(RemovedCodeEnum.AVAILABLE.getCode());
            repository.save(authAccountRole);
        }
    }

    //批量删除该角色下用户
    public void batchDeleteRole(String[] accountIds,String roleId) {
        List<String> list = Arrays.asList(accountIds);
        for(String accountId:list){
            repository.delete(repository.findByAccountRoleId(accountId,roleId));
        }
    }
}
